package com.example.couponservice.controller;

import com.example.couponservice.domain.dto.CouponDto;
import com.example.couponservice.domain.entity.Coupon;
import com.example.couponservice.service.ICouponService;
import com.example.couponservice.utils.CurrentHoler;
import com.example.couponservice.utils.Result;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.time.LocalDateTime;
import java.util.List;

@RestController
@RequestMapping("/coupon")
public class CouponController {

    @Autowired
    private ICouponService couponService;

    /**
     * 获取所有可用优惠券
     *
     * @return 包含优惠券列表的响应结果
     */
    @GetMapping
    public Result getAllCoupon() {
        // 调用服务层获取所有优惠券，传入当前时间和当前用户ID
        List<CouponDto> couponDtos = couponService.getAllCoupon(LocalDateTime.now(), CurrentHoler.getCurrentId());
        return Result.success(couponDtos);
    }

    /**
     * 用户领取优惠券
     *
     * @param id 优惠券ID
     * @return 领取结果
     * @throws RuntimeException 当优惠券不存在、被禁用、未开始、已结束或无库存时抛出异常
     */
    @PostMapping("/{id}")
    public Result gainCoupon(@PathVariable Integer id) {
        // 校验优惠券是否存在
        Coupon coupon = couponService.getById(id);
        if (coupon == null) throw new RuntimeException("该优惠券不存在");

        // 校验优惠券状态
        if (coupon.getStatus() == 0) throw new RuntimeException("该优惠卷被禁用了");

        // 校验优惠券时间范围
        if (coupon.getStartTime().isAfter(LocalDateTime.now())) throw new RuntimeException("特惠还未开始");
        if (coupon.getEndTime().isBefore(LocalDateTime.now())) throw new RuntimeException("特惠已结束");

        // 校验库存
        if (coupon.getStock() <= 0) throw new RuntimeException("该优惠卷卖完了！");

        // 执行领取逻辑
        couponService.addCouponToUser(id);
        return Result.success();
    }
}